package logic

import (
	"context"
	"errors"
	"month_zg5/book_srv/models"
	book_rpc "month_zg5/book_srv/proto"
	"month_zg5/book_srv/service/mysql"
)

// 注册
func (b *BookRpc) Register(ctx context.Context, in *book_rpc.RegisterReq) (*book_rpc.RegisterRes, error) {
	//判断账号是否被注册
	_, err := mysql.GetUserByUsername(in.Username)
	if err == nil {
		return &book_rpc.RegisterRes{}, errors.New("账号已经被注册")
	}
	user, err := mysql.RegisterUser(&models.User{
		Username: in.Username,
		Password: in.Password,
		Email:    in.Email,
		Phone:    in.Phone,
	})
	if err != nil {
		return &book_rpc.RegisterRes{}, errors.New("账号注册失败")
	}
	return &book_rpc.RegisterRes{Userid: int32(user.ID)}, nil
}

// 登录
func (b *BookRpc) UserLogin(ctx context.Context, in *book_rpc.UserLoginReq) (*book_rpc.UserLoginRes, error) {
	user, err := mysql.GetUserByUsername(in.Username)
	if err != nil {
		return &book_rpc.UserLoginRes{}, err
	}
	return &book_rpc.UserLoginRes{Userid: int32(user.ID), Password: user.Password}, nil
}
